package com.ruoyi.web.controller.tool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;

/**
 * SpreadJS文件上传下载处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/tool/spreadjs")
public class SpreadJSController
{
    private static final Logger log = LoggerFactory.getLogger(SpreadJSController.class);

    @Autowired
    private ServerConfig serverConfig;

    /**
     * SpreadJS附件上传
     * 
     * @param file 上传的文件
     * @return 文件信息（包含下载URL）
     */
    @PostMapping("/upload")
    public AjaxResult uploadAttachment(MultipartFile file) throws Exception
    {
        try
        {
            // 上传到spreadjs专用目录
            String filePath = RuoYiConfig.getProfile() + "/spreadjs";
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            
            log.info("SpreadJS文件上传成功: {}, 访问路径: {}", file.getOriginalFilename(), url);
            
            return ajax;
        }
        catch (Exception e)
        {
            log.error("SpreadJS文件上传失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * SpreadJS附件下载
     * 
     * @param resource 文件路径
     * @param response HTTP响应对象
     */
    @GetMapping("/download")
    public void downloadAttachment(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (StringUtils.isEmpty(resource))
            {
                throw new Exception("资源文件不能为空");
            }
            
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + FileUtils.stripPrefix(resource);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
            
            log.info("SpreadJS文件下载成功: {}", downloadName);
        }
        catch (Exception e)
        {
            log.error("SpreadJS文件下载失败", e);
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("文件下载失败：" + e.getMessage());
        }
    }
}
